import subprocess
import time
from pathlib import Path
import config
import logging
import os
import platform
import signal

logger = logging.getLogger(__name__)

class LogcatCatcher:
    def __init__(self, device_serial: str):
        self.device_serial = device_serial
        self.logcat_process = None  # 保存logcat子进程
        self.log_file = None  # 日志文件路径
        self.log_file_handle = None  # 新增：保存文件句柄

    def start(self):
        """启动logcat抓取"""
        config.REPORT_LOGCAT_DIR.mkdir(parents=True, exist_ok=True)  # 依赖config的目录初始化
        timestamp = time.strftime("%Y%m%d%H%M%S")
        self.log_file = config.REPORT_LOGCAT_DIR / f"logcat_{self.device_serial}_{timestamp}.log"

        # 打开文件并保存句柄（关键修改）
        self.log_file_handle = open(self.log_file, "w", encoding="utf-8")

        cmd = [
            "adb", "-s", self.device_serial, "logcat", "-c",
            "&&", "adb", "-s", self.device_serial, "logcat", "-v", "time"
        ]

        self.logcat_process = subprocess.Popen(
            " ".join(cmd),
            shell=True,
            stdout=self.log_file_handle,  # 使用保存的句柄
            stderr=subprocess.STDOUT
        )
        logger.info(f"📱 已启动logcat抓取，设备: {self.device_serial}，日志路径: {self.log_file}")

    def stop(self):
        """停止logcat抓取并彻底终止子进程"""
        try:
            if self.logcat_process and self.logcat_process.poll() is None:
                # 关键修改：根据系统类型强制终止所有子进程
                if platform.system() == "Windows":
                    # Windows使用taskkill终止进程树
                    subprocess.run(
                        ["taskkill", "/F", "/T", "/PID", str(self.logcat_process.pid)],
                        stdout=subprocess.DEVNULL,
                        stderr=subprocess.DEVNULL
                    )
                else:
                    # Linux/macOS使用killpg终止进程组
                    os.killpg(os.getpgid(self.logcat_process.pid), signal.SIGTERM)

                self.logcat_process.wait(timeout=5)  # 等待进程退出
        except subprocess.TimeoutExpired:
            logger.warning("logcat子进程超时未终止，尝试强制终止")
            self.logcat_process.kill()  # 最终强制杀死
        finally:
            if self.log_file_handle:
                try:
                    if not self.log_file_handle.closed:
                        self.log_file_handle.close()
                except Exception as e:
                    logger.error(f"关闭文件句柄失败: {str(e)}")

    def get_log_path(self) -> str:
        return self.log_file.as_uri() if self.log_file else "日志未生成"